package models

import (
	"time"

	"gorm.io/gorm"
)

type Role struct {
	ID          uint           `json:"id" gorm:"primaryKey"`
	Name        string         `json:"name" gorm:"uniqueIndex;size:50;not null" binding:"required"`
	DisplayName string         `json:"display_name" gorm:"size:100;not null" binding:"required"`
	Description string         `json:"description" gorm:"type:text"`
	Status      string         `json:"status" gorm:"type:enum('active','inactive');default:'active'"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 统计字段（不存储在数据库中）
	PermissionCount int `json:"permission_count" gorm:"-"`
	UserCount       int `json:"user_count" gorm:"-"`

	// 关联
	Permissions []Permission `json:"permissions" gorm:"many2many:role_permissions;"`
	Users       []User       `json:"users" gorm:"many2many:user_roles;"`
}

type UserRole struct {
	ID         uint      `json:"id" gorm:"primaryKey"`
	UserID     uint      `json:"user_id" gorm:"not null"`
	RoleID     uint      `json:"role_id" gorm:"not null"`
	AssignedBy *uint     `json:"assigned_by"`
	AssignedAt time.Time `json:"assigned_at"`

	// 关联
	User           User  `json:"user" gorm:"foreignKey:UserID"`
	Role           Role  `json:"role" gorm:"foreignKey:RoleID"`
	AssignedByUser *User `json:"assigned_by_user" gorm:"foreignKey:AssignedBy"`
}

type RolePermission struct {
	ID           uint      `json:"id" gorm:"primaryKey"`
	RoleID       uint      `json:"role_id" gorm:"not null"`
	PermissionID uint      `json:"permission_id" gorm:"not null"`
	CreatedAt    time.Time `json:"created_at"`

	// 关联
	Role       Role       `json:"role" gorm:"foreignKey:RoleID"`
	Permission Permission `json:"permission" gorm:"foreignKey:PermissionID"`
}

// TableName 指定表名
func (Role) TableName() string {
	return "roles"
}

func (Permission) TableName() string {
	return "permissions"
}

func (RolePermission) TableName() string {
	return "role_permissions"
}

// BeforeCreate 创建前钩子
func (r *Role) BeforeCreate(tx *gorm.DB) error {
	if r.Status == "" {
		r.Status = "active"
	}
	return nil
}

// HasPermission 检查角色是否有指定权限
func (r *Role) HasPermission(db *gorm.DB, permission string) bool {
	var count int64
	db.Table("permissions p").
		Joins("JOIN role_permissions rp ON p.id = rp.permission_id").
		Where("rp.role_id = ? AND p.name = ?", r.ID, permission).
		Count(&count)
	return count > 0
}

// GetPermissions 获取角色所有权限
func (r *Role) GetPermissions(db *gorm.DB) []Permission {
	var permissions []Permission
	db.Table("permissions p").
		Joins("JOIN role_permissions rp ON p.id = rp.permission_id").
		Where("rp.role_id = ?", r.ID).
		Find(&permissions)
	return permissions
}

// AssignPermission 分配权限给角色
func (r *Role) AssignPermission(db *gorm.DB, permissionID uint) error {
	rolePermission := RolePermission{
		RoleID:       r.ID,
		PermissionID: permissionID,
	}
	return db.FirstOrCreate(&rolePermission, rolePermission).Error
}

// RemovePermission 移除角色权限
func (r *Role) RemovePermission(db *gorm.DB, permissionID uint) error {
	return db.Where("role_id = ? AND permission_id = ?", r.ID, permissionID).
		Delete(&RolePermission{}).Error
}
